package com.yhny.lykj.yuhannongye.ui;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.longsichao.lscframe.ctrl.DataManager;
import com.longsichao.lscframe.model.LSCModel;
import com.longsichao.lscframe.net.HttpConnection;
import com.longsichao.lscframe.view.LSCToast;
import com.yhny.lykj.yuhannongye.Adapter.ShopInfoAdapter;
import com.yhny.lykj.yuhannongye.R;
import com.yhny.lykj.yuhannongye.app.BaseActivity;
import com.yhny.lykj.yuhannongye.app.BaseRefreshListAdapter;
import com.yhny.lykj.yuhannongye.app.LSCGridLayoutManager;
import com.yhny.lykj.yuhannongye.app.UserConfig;
import com.yhny.lykj.yuhannongye.model.BaseModel;
import com.yhny.lykj.yuhannongye.model.CarListModel;
import com.yhny.lykj.yuhannongye.model.ShopInfoModel;
import com.yhny.lykj.yuhannongye.model.ShopInfoPostModel;
import com.yhny.lykj.yuhannongye.model.ShopListModel;
import com.yhny.lykj.yuhannongye.net.NetHelper;
import com.yhny.lykj.yuhannongye.tools.LCLog;
import com.yhny.lykj.yuhannongye.tools.Tools;
import com.yhny.lykj.yuhannongye.view.SlideShowView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

public class ShopListActivity extends BaseActivity implements PopupWindow.OnDismissListener {
    private SlideShowView slideShowView;
    private TextView shopNameView;
    private TextView shopunPriceView;
    private WebView webView;
    private int num = 1;
    private String id = "";//商品id
    private ShopInfoModel shopInfoModel;//商品信息

    private List<String> array;
    private TextView numView;
    private ImageView carBt;
    private PopupWindow popMenu;
    ArrayList<ShopInfoPostModel.ListEntity> list;

    private RelativeLayout rightRroup;

    private int fromView = 1;
    private String phone;
    private int fromType = -1;

    private int selectButton = -1;//当前所选按钮，加入购物车/立即购买
    private int selectCar = 1;//加入购物车
    private int selectBuy = 2;//立即购买

    private double totalPrice = 0.00;// 购买的商品总价

    private RecyclerView hotListView;
    private ShopInfoAdapter hotListAdapter;
    private List<ShopListModel.ListEntity> hotList;
    TextView newsTv;
    TextView hotTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_list);
        id = getIntent().getStringExtra(SHOP_ID);
        phone = getIntent().getStringExtra(SHOPER_PHONE);
        fromView = getIntent().getIntExtra(SHOP_FROM,SHOP_LIST);
        fromType = getIntent().getIntExtra(FROM_TYPE_ID,-1);//来源页面
        TextView textView = (TextView)findViewById(R.id.name_top_bar);
        rightRroup = (RelativeLayout)findViewById(R.id.right_group);
        rightRroup.setOnClickListener(this);
        findViewById(R.id.left_group).setOnClickListener(this);
        findViewById(R.id.left_text).setOnClickListener(this);
        textView.setText("商品详情");

        findViewById(R.id.shop_add_car).setOnClickListener(this);


        newsTv = (TextView) findViewById(R.id.goods_news);
        newsTv.setOnClickListener(this);
        hotTv = (TextView)findViewById(R.id.goods_hots);
        hotTv.setOnClickListener(this);


        carBt = (ImageView)findViewById(R.id.shop_add_coll);
        carBt.setOnClickListener(this);
        slideShowView = (SlideShowView)findViewById(R.id.slideshowView);

        findViewById(R.id.shop_buy).setOnClickListener(this);//立即购买

        webView = (WebView)findViewById(R.id.webview);
        webView.getSettings().setAllowFileAccess(false);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setJavaScriptEnabled(false);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.setWebViewClient(new MyWebViewClient());
//        webView.addJavascriptInterface(new JavaScriptInterface(this), "imagelistner");//这个是给图片设置点击监听的，如果你项目需要webview中图片，点击查看大图功能，可以这么添加
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        shopNameView = (TextView)findViewById(R.id.shop_name);
        shopunPriceView = (TextView)findViewById(R.id.shop_text2);
//        shopunPriceView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );

        //精选每日
        hotListView = (RecyclerView) findViewById(R.id.home_day);
        final LSCGridLayoutManager layoutManager1 = new LSCGridLayoutManager(this,2);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        hotListView.setLayoutManager(layoutManager1);
        hotListView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).sizeResId(R.dimen.item_vertical_margin_h).colorResId(R.color.white).build());
        hotList = new ArrayList<>();
        hotListAdapter = new ShopInfoAdapter(hotList);
        hotListAdapter.setOnItemClickListener(new BaseRefreshListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(ShopListActivity.this,ShopListActivity.class);
                intent.putExtra(SHOP_FROM,SHOP_LIST);
                intent.putExtra(SHOP_ID,hotList.get(position).goodsid);
                startActivity(intent);
            }
        });
        hotListView.setAdapter(hotListAdapter);

        showProgressDialog(R.string.text_loading);
        //商品详情 用户评价
        DataManager.getData(MODEL_PROCESS_0, NetHelper.Shop.getShopInfo(id), this);
        //热门
        DataManager.getData(MODEL_PROCESS_3, NetHelper.Shop.searchgoodsnewlist(), this);
    }
    @Override
    public boolean onModel(int caseId, LSCModel model) {
        if (super.onModel(caseId, model)) {
            dismissProgressDialog();
            return false;
        }
        switch (caseId){
            case MODEL_PROCESS_3:{
                //猜你喜欢
                ShopListModel shopListModel = (ShopListModel)model;
                if (isDataEmpty(shopListModel)||shopListModel.data==null||shopListModel.data.isEmpty()) {
                } else {
                    hotList.clear();
                    hotList.addAll(shopListModel.data);
                    hotListAdapter.notifyDataSetChanged();
                }
                break;
            }
            case MODEL_PROCESS_0:{
                shopInfoModel = (ShopInfoModel)model;
                if (!isDataEmpty(shopInfoModel)&&shopInfoModel.status==1){
                    shopNameView.setText(shopInfoModel.data.name);
                    shopunPriceView.setText("原价："+shopInfoModel.data.goodsprice+"元 / "+ shopInfoModel.data.goodsunit);//原价
                    LCLog.e(Tools.HtmlToString(shopInfoModel.data.goodsdescribe));
                    webView.loadDataWithBaseURL("about:blank", Tools.HtmlToString(shopInfoModel.data.goodsdescribe), "text/html", "utf-8", null);
                    //轮播图
                    array = new ArrayList<>();
                    if (shopInfoModel.data!=null&&!TextUtils.isEmpty(shopInfoModel.data.goodspic)){
                            array.add(shopInfoModel.data.goodspic);
                        slideShowView.setAutoPlay(true);
                        slideShowView.startPlay();
                        slideShowView.setImageList(array);
                    }
                }else{
                    LSCToast.show(this,"获取信息失败！");
                }
                break;
            }
        }
        dismissProgressDialog();
        return false;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.goods_news:{
                      //最新
                newsTv.setTextColor(getResources().getColor(R.color.ItemTitle));
                hotTv.setTextColor(getResources().getColor(R.color.white));
                DataManager.getData(MODEL_PROCESS_3, NetHelper.Shop.searchgoodsnewlist(), this);
                break;
            }
            case R.id.goods_hots:{
                //热门
                hotTv.setTextColor(getResources().getColor(R.color.ItemTitle));
                newsTv.setTextColor(getResources().getColor(R.color.white));
                DataManager.getData(MODEL_PROCESS_3, NetHelper.Shop.getLikeList(1), this);
                break;
            }
            case R.id.left_group:
            case R.id.left_text:{
                finish();
                break;
            }

            case R.id.pop_add:{
                num++;
                numView.setText(""+num);
                break;
            }
            case R.id.pop_reduce:{
                num--;
                if (num<1){
                    num = 1;
                }
                numView.setText(""+num);
                break;
            }
            case R.id.pop_submit:{


                if (selectButton==selectBuy){
                    //总金额
                        totalPrice += shopInfoModel.data.goodsprice * num;
                    //立即购买
                    Intent intent = new Intent(ShopListActivity.this,OrderInfoActivity.class);
                    intent.putExtra(CAR_LIST_DATA,  calculateShop());
                    intent.putExtra(CAR_LIST_PRICE,  ""+totalPrice);
                    intent.putExtra(CAR_LIST_ID,  "");
                    intent.putExtra(FROM_TYPE_ID,FROM_TYPE_VIEW_CAR_LIST);
                    startActivity(intent);
                }else{
                    //加入购物车
                    addCar(id,numView.getText().toString());
                }

                popMenu.dismiss();
                break;
            }
            case R.id.shop_add_car:{
                //加入购物车
                if (TextUtils.isEmpty(UserConfig.getConfigUserId())){
                    Intent intent = new Intent(this,LoginActivity.class);
                    startActivity(intent);
                }else{
                    selectButton = selectCar;
                    initPopMenu();
                }
                break;
            }
        }
        super.onClick(v);
    }


    private CarListModel carSmlpeList = new CarListModel();

    /**
     * @return
     */
    private String calculateShop()
    {
        String json = "";
        carSmlpeList = new CarListModel();
        carSmlpeList.list = new ArrayList<>();
        CarListModel.ListEntity shoper = new CarListModel.ListEntity();
        Gson gson = new Gson();
        json = gson.toJson(carSmlpeList);
        return json;
    }
    private void addCar(String goodsid,String goodsNum){
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("action", "addship");
        builder.addFormDataPart("userid", UserConfig.getConfigUserId());
        builder.addFormDataPart("goodsid", goodsid);
        builder.addFormDataPart("goodsnum", goodsNum);
        Request request = new Request.Builder().url(NetHelper.Car.addCar(goodsid,goodsNum).getUrl()).post(builder.build()).build();
        HttpConnection.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        LSCToast.show(ShopListActivity.this, "添加失败!");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String string = response.body().string();
                LCLog.e("string = "+string);
                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        if (!Tools.isGoodJson(string)){
                            LSCToast.show(ShopListActivity.this, "服务器请求失败!");
                            LCLog.e("string = "+string);
                        }else {
                            Gson gson = new GsonBuilder().serializeNulls().create();
                            BaseModel userInfo = gson.fromJson(string, BaseModel.class);
                            if (userInfo == null&&userInfo.status!=1) {
                                LSCToast.show(ShopListActivity.this, "添加失败!");
                                LCLog.e("string = "+string);
                            } else {
                                LSCToast.show(ShopListActivity.this, "添加成功！");
                            }
                        }
                    }
                });
            }
        });

    }
    private void initPopMenu(){
        //防止重复按按钮
        if (popMenu != null && popMenu.isShowing()) {
            return;
        }
        View contentView = View.inflate(this, R.layout.pop_shop_info,
                null);
        popMenu = new PopupWindow(contentView, RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        popMenu.setBackgroundDrawable(new BitmapDrawable());
        //设置点击弹窗外隐藏自身
        popMenu.setFocusable(true);
        popMenu.setOutsideTouchable(true);
        //设置动画
        popMenu.setAnimationStyle(R.style.PopupWindow);
        //设置位置
        popMenu.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
        //设置消失监听
        popMenu.setOnDismissListener(this);
        //设置PopupWindow的View点击事件
        setOnPopupViewClick(contentView);
        //设置背景色
        setBackgroundAlpha(0.5f);


    }

    private void setOnPopupViewClick(View view) {
        view.findViewById(R.id.pop_add).setOnClickListener(this);
        view.findViewById(R.id.pop_reduce).setOnClickListener(this);
        view.findViewById(R.id.pop_submit).setOnClickListener(this);
        numView = (TextView)view.findViewById(R.id.pop_num);

    }

    //设置屏幕背景透明效果
    public void setBackgroundAlpha(float alpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = alpha;
        getWindow().setAttributes(lp);
    }


    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            imgReset();//重置webview中img标签的图片大小
            // html加载完成之后，添加监听图片的点击js函数
//            addImageClickListner();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     **/
    private void imgReset() {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                "}" +
                "})()");
    }
    private void addImageClickListner() {
        // 这段js函数的功能就是，遍历所有的img节点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }

    @Override
    protected void onDestroy() {
        webView.destroy();
        slideShowView.setAutoPlay(false);
        slideShowView.stopPlay();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        webView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        carSmlpeList = new CarListModel();
        totalPrice = 0;
        slideShowView.setAutoPlay(true);
        slideShowView.startPlay();
        webView.onResume();

        super.onResume();
    }

    @Override
    public void onDismiss() {
        setBackgroundAlpha(1);
    }

}
